# -*- coding: utf-8 -*-
class AdminController < ApplicationController
  before_filter :employee_authorize
  before_filter :sys_before_log
  before_filter :employee_action_hx
  before_filter :privilege_filter,:except=>[:getRolePrivilegeById,:getRolePrivilegeDetailsById,:clearTestDataView,:reindexView,:calCostPriceView,:roleWarehouse,:getRoleWarehouse,:roleWarehouseLock]

  #显示清空数据的网页介面。
  def clearTestDataView
    
  end

  #角色设置
  def rolePrivilege
    
  end

  #显示添加角色页面
  def newRole
    
  end

  #显示编辑角色页面
  def editRole
    
  end

  #系统日志。
  def logList
    
  end

  #登录日志
  def loginLogList
    
  end

  #数据维护
  def dataManager
    
  end

  #用户自行修改密码的介面
  def changePasswordView
    
  end
  
  #得到所有的根模块
  def getAllModules
    modules = Privilege.find(:all,:conditions=>['parent_id = 0'],:order=>'sort_id')
    jsonStr="{totalProperty:"+modules.length.to_s+",root:"+modules.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #
  def getAllSysControllers
    sysControllers = SysController.find(:all,:order=>'name')
    jsonStr="{totalProperty:"+sysControllers.length.to_s+",root:"+sysControllers.to_json()+"}"
    logger.debug jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #
  def getAllSysActions
    if params[:sys_controller_id] == nil
      sysActions = SysAction.find(:all,:order=>'name')
    else
      sysActions = SysAction.find(:all,:conditions=>["sys_controller_id = ?",params[:sys_controller_id]],:order=>'name')
    end    
    jsonStr="{totalProperty:"+sysActions.length.to_s+",root:"+sysActions.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #
  def getAllSysLog
    start = params[:start]
    limit = params[:limit]
    dblogs = DbLog.paginate start,limit

    jsonStr="{totalProperty:"+DbLog.count.to_s+",root:"+dblogs.to_json(:include=>[:company,:department,:employee])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #获得系统登录日志
  def getAllSysLoginLog
    name =  params[:name]
    if name == nil || name == ''
      count = LoginLog.count
      loginLogs = LoginLog.find(
        :all,
        :offset => params[:start].to_i,
        :include=>[:company,:department,:employee],
        :limit => params[:limit].to_i,
        :order=> "id DESC"
      )
    else
      name = '%'+name+'%'
      count = LoginLog.find(
        :all,
        :select => 'id',
        :conditions=> ['name like ?',name],
        :order=> "id DESC"
      ).count
      
      loginLogs = LoginLog.find(
        :all,
        :offset => params[:start].to_i,
        :conditions=> ['name like ?',name],
        :include=>[:company,:department,:employee],
        :limit => params[:limit].to_i,
        :order=> "id DESC"
      )
    end
    jsonStr="{totalProperty:"+count.to_s+",root:"+loginLogs.to_json(:include=>[:company,:department,:employee])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #得到所有的用户行为日志
  def getAllActionHxes
    start = params[:start]
    limit = params[:limit]
    employeeId = params[:employee_id]
    employeeActionHxes = EmployeeActionHx.paginate employeeId,start.to_i,limit.to_i
    pageCount = EmployeeActionHx.page_count employeeId
    jsonStr="{totalProperty:"+pageCount.count.to_s+",root:"+employeeActionHxes.to_json(:include=>[:company,:department,:employee,:role])+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #根据ID得到角色权限树
  def getRolePrivilegeById
    if params[:role_id] == nil
      render :text=>"[{}]", :layout=>false
      return
    end
    nodeId =  params["node"]
    #作一些处理，因为传来的nodeId可能出现怪值。
    if nodeId == nil || (nodeId.include? "xnode-") || nodeId == "0" || nodeId == 0
      is_root = true
      nodeId = 0
    end
    roleId = params[:role_id]
    #privileges  = Privilege.find(:all,:conditions=>["parent_id = ? AND is_locked = 0",nodeId],:order=>'sort_id')
    if nodeId == 0
      privileges  = Privilege.find(:all,:select=>'p.id,p.name,p.level,p.is_locked,orpd.allow_show',:conditions=>["p.parent_id = ? AND p.is_locked = 0",nodeId],:joins=>"p left join (select distinct rpd.module_id,rpd.allow_show,ip.id from privileges ip left join roles_privilege_details rpd on ip.id = rpd.module_id where rpd.role_id = #{roleId} AND ip.parent_id = 0 AND ip.is_locked = 0) orpd on p.id = orpd.id",:order=>'sort_id')
    else
      privileges  = Privilege.find(:all,:select=>'p.id,p.name,p.level,p.is_locked,orpd.allow_show',:conditions=>["p.parent_id = ? AND p.is_locked = 0",nodeId],:joins=>"p left join (select distinct rpd.menu_id,rpd.allow_show,ip.id from privileges ip left join roles_privilege_details rpd on ip.id = rpd.menu_id where rpd.role_id = #{roleId} AND ip.parent_id <> 0 AND ip.is_locked = 0) orpd on p.id = orpd.id",:order=>'sort_id')
    end
    treeData="["
    privileges.each do |privilege|
      #treeData.concat("{id:#{privilege.id},text:\"#{privilege.name}\",leaf:#{privilege.leaf}},")
      treeData.concat("{id:#{privilege.id},text:\"#{privilege.name}\"")
      if privilege.level == 0
        treeData.concat(",leaf:false")
      else
        treeData.concat(",leaf:true")
      end
      #if privilege.is_locked == 1
      if privilege.allow_show == "1" || privilege.allow_show == 1
        treeData.concat(",\"checked\":true},")
      else
        treeData.concat(",\"checked\":false},")
      end
    end
    treeData = treeData[0,treeData.size-1]
    treeData.concat("]")
    logger.info treeData
    jsonStr = treeData
    render :text=>jsonStr, :layout=>false
  end


  #得到某一权限下，某角色的详细项。
  def getRolePrivilegeDetailsById    
    #此处要得到3个参加1.公司，2.角色，3.权限
    logger.info "++++++++++++++++++++++++++++++++++++++++++++++++++++++"
    logger.info params[:role_id]
    role = Role.find(params[:role_id])
    #在这里，角色中的privilege已经深化为menu_id，是一系列相关权限细节的集合
    rolePrivilegeDetails = RolesPrivilegeDetail.find(:all,:conditions=>["menu_id = ? AND role_id = ?",params[:privilege_id],params[:role_id]])
    #同时也要得到系统中的权限细节，然后用系统中的权限细节和个人的权限细节进行对比，有则不动，无则加，如果角色有，系统没有，则删。、
    Privilege.transaction do
      sysPrivilegeDetails = Privilege.getUnlockedSysPrivilegeDetailsForRole(params[:privilege_id])
    
      if sysPrivilegeDetails != nil
        #如果此时角色还没有分配过权限细节，则把现有系统权限一次性追加上。
        if rolePrivilegeDetails.length == 0
          sysPrivilegeDetails.each do |sysPrivilegeDetail|
            rolesPrivilegeDetail = RolesPrivilegeDetail.new
            rolesPrivilegeDetail.company_id = session[:company_id]
            rolesPrivilegeDetail.module_id = params[:parent_privilege_id]
            rolesPrivilegeDetail.menu_id = params[:privilege_id]
            rolesPrivilegeDetail.privilege_detail_id  = sysPrivilegeDetail.id
            role.roles_privilege_details << rolesPrivilegeDetail
          end
        else
          #分二次循环，一是查是否有多的，第二次是查是滞有少的。
          #有不动，少则加，多则删
          #privilegeAction有三个值，1.add,2.remove,3.nil,""就是无动作
          privilegeAction = nil
          rolePrivilegeDetails.each do |rolePrivilegeDetail|
            privilegeAction = "remove"
            sysPrivilegeDetails.each do |sysPrivilegeDetail|
              if rolePrivilegeDetail.privilege_detail_id ==  sysPrivilegeDetail.id
                privilegeAction = nil
              end
            end
            if privilegeAction == "remove"
              rolePrivilegeDetails.delete(rolePrivilegeDetail)
            end
          end
          #第二次循环，就是添加
          privilegeAction = nil
          sysPrivilegeDetails.each do |sysPrivilegeDetail|
            privilegeAction = "add"
            rolePrivilegeDetails.each do |rolePrivilegeDetail|
              if rolePrivilegeDetail.privilege_detail_id ==  sysPrivilegeDetail.id
                privilegeAction = nil
              end
            end
            if privilegeAction == "add"
              rolesPrivilegeDetail = RolesPrivilegeDetail.new
              rolesPrivilegeDetail.company_id = session[:company_id]
              rolesPrivilegeDetail.module_id = params[:parent_privilege_id]
              rolesPrivilegeDetail.menu_id = params[:privilege_id]
              rolesPrivilegeDetail.privilege_detail_id  = sysPrivilegeDetail.id
              role.roles_privilege_details << rolesPrivilegeDetail
            end
          end
        end      
      end
    end
    
    rolePrivilegeDetails = RolesPrivilegeDetail.find(:all,:include => [:privilege_detail],:conditions=>["menu_id = ? AND role_id = ?",params[:privilege_id],params[:role_id]])
    jsonStr="{totalProperty:"+rolePrivilegeDetails.length.to_s+",root:"+rolePrivilegeDetails.to_json(:include=>[:privilege_detail])+"}"
    render :text=>jsonStr, :layout=>false
  end

  

  #角色的解锁与锁定
  def roleLock    
    role = Role.find(params[:id])
    if role.is_locked == 1
      role.is_locked = 0
    else
      role.is_locked = 1
    end
    role.save
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end


  #得到某一公司下的所有角色
  def getAllRoles
    forCBB = params[:for_cbb]
    if forCBB == 'true'
      roles = Role.find(:all,:conditions=>["company_id = ? AND is_locked = 0",session[:company_id]])
    else
      roles = Role.find(:all,:conditions=>["company_id = ?",session[:company_id]])
    end   
    
    jsonStr="{totalProperty:"+roles.length.to_s+",root:"+roles.to_json()+"}"
    render :text=>jsonStr, :layout=>false
  end

  def createRole
    role = Role.new
    role.name = params[:name]
    role.company_id = session[:company_id]
    role.cross_dept_sale_order_query = params[:cross_dept_sale_order_query]
    role.financial_management = params[:financial_management]
    role.check_cost_price = params[:check_cost_price]
    role.unsafe_discount_audit = params[:unsafe_discount_audit]
    role.discount = params[:discount]
    role.description = params[:description]
    role.save
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  def getRoleById    
    role = Role.find(params[:id])
    rootStr = role.to_json()
    jsonStr = "{root:["+rootStr+"]}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #把编辑后的数据，更新到数据库中
  def updateRole
    
    begin
      role = Role.find(params[:id])
      role.name = params[:name]
      role.cross_dept_sale_order_query = params[:cross_dept_sale_order_query]
      role.financial_management = params[:financial_management]
      role.check_cost_price = params[:check_cost_price]
      role.unsafe_discount_audit = params[:unsafe_discount_audit]
      role.discount = params[:discount]
      role.description = params[:description]
      role.save!
      info = "成功"
    rescue Exception => e
      info = e.to_s
      logger.info info
      DbLog.info(session[:company_id], session[:department_id], session[:employee_id], params[:controller], params[:action], request.remote_ip ,e.to_s)
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到个人的权限
  def getPersonPrivileges
    
    roleId = session[:role_id]
    companyId = session[:company_id]
    #rolesPrivilegeDetails = RolesPrivilegeDetail.find(:all,:select=>"distinct privilege_id",:order => "id",:conditions=>["role_id = ? AND company_id = ? AND is_locked = 0",roleId,companyId])
    rolesPrivilegeDetails = RolesPrivilegeDetail.find_by_sql("select distinct pd.privilege_id as privilege_id,p.name as name from roles_privilege_details pd,privileges p where p.level = 0 AND pd.privilege_id = p.id AND pd.role_id = #{roleId} AND pd.company_id = #{companyId}")
    jsonStr="{totalProperty:"+rolesPrivilegeDetails.length.to_s+",root:"+rolesPrivilegeDetails.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #清空测试数据,此方法会清空的表包括，出，入库，调拨，拆分，组合，退货，期初，盘点表 , 销售表，采购表。
  def clearTestData
    begin
      DeliveryOrder.destroy_all()
      WarehousingEntry.destroy_all()
      TransferOrder.destroy_all()
      SeparateOrder.destroy_all()
      AssemblyOrder.destroy_all()
      SaleReturned.destroy_all()
      PurchaseReturned.destroy_all()
      OpeningStock.destroy_all()
      Inventory.destroy_all()
      PurchaseOrder.destroy_all()
      SaleOrder.destroy_all()
      ProductCollection.destroy_all()
      Receivable.destroy_all()
      Payable.destroy_all()
      Claim.destroy_all()
      ClaimReturned.destroy_all()
      Loan.destroy_all()
      LoanDelivery.destroy_all()
      LoanReturned.destroy_all()
      LoanReturnedDetail.destroy_all()
      
      SaleOrderHx.destroy_all()
      PurchaseOrderHx.destroy_all()
      DeliveryOrderHx.destroy_all()
      WarehousingEntryHx.destroy_all()
      LoanHx.destroy_all()
      LoanDeliveryHx.destroy_all()
      LoanReturnedHx.destroy_all()
      OpeningStockHx.destroy_all()
      InventoryHx.destroy_all()
      SysRemindRegister.destroy_all()
      EmployeeActionHx.destroy_all()
      CostPrice.destroy_all()
      Sequence.update_all("seq_no = 0" )
      AdvancePayment.destroy_all()
      
      info = "成功"
    rescue Exception => e
      info = "error"
      logger.info e
    end
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #显示某个角色所订阅的系统提醒
  def sysRemindForRole
    #得到某个角色，已经定义的系统提醒。
    @sysRemindRegisters =  SysRemindRegister.find(:all,:conditions=>["company_id = ? AND role_id = ?",session[:company_id],params[:id]])
  end

  #为角色更新订阅状态
  def updateSysRemindForRole
    logger.info params[:sale_order_audit] == nil
    logger.info params[:product_stock] == nil
    #如果没有选择，那么就设置为0，为0时，如果没个记录，那不必设置了。
    #如果选择了，那么就设置为1，为1时，如果没有这个记录，就要插入一条新记录
    roleId = params[:id]
    if params[:sale_order_audit] == nil
      sysRemindRegister = SysRemindRegister.find(:first,:conditions=>["company_id = ? AND name = '销售订单审批' AND role_id = ?",session[:company_id],roleId])
      if sysRemindRegister != nil
        sysRemindRegister.is_register = 0
        sysRemindRegister.save!
      end
    else
      sysRemindRegister = SysRemindRegister.find(:first,:conditions=>["company_id = ? AND name = '销售订单审批' AND role_id = ?",session[:company_id],roleId])
      if sysRemindRegister == nil
        sysRemindRegister = SysRemindRegister.new
        sysRemindRegister.company_id = session[:company_id]
        sysRemindRegister.role_id = roleId
        sysRemindRegister.name = '销售订单审批'
        sysRemindRegister.is_register = 1
        sysRemindRegister.save!
      else
        sysRemindRegister.is_register = 1
        sysRemindRegister.save!
      end
    end

    #销售出库
    if params[:sale_order_delivery] == nil
      sysRemindRegister = SysRemindRegister.find(:first,:conditions=>["company_id = ? AND name = '销售订单出库' AND role_id = ?",session[:company_id],roleId])
      if sysRemindRegister != nil
        sysRemindRegister.is_register = 0
        sysRemindRegister.save!
      end
    else
      sysRemindRegister = SysRemindRegister.find(:first,:conditions=>["company_id = ? AND name = '销售订单出库' AND role_id = ?",session[:company_id],roleId])
      if sysRemindRegister == nil
        sysRemindRegister = SysRemindRegister.new
        sysRemindRegister.company_id = session[:company_id]
        sysRemindRegister.role_id = roleId
        sysRemindRegister.name = '销售订单出库'
        sysRemindRegister.is_register = 1
        sysRemindRegister.save!
      else
        sysRemindRegister.is_register = 1
        sysRemindRegister.save!
      end
    end

    #借货归还
    if params[:loan_returned] == nil
      sysRemindRegister = SysRemindRegister.find(:first,:conditions=>["company_id = ? AND name = '借货归还' AND role_id = ?",session[:company_id],roleId])
      if sysRemindRegister != nil
        sysRemindRegister.is_register = 0
        sysRemindRegister.save!
      end
    else
      sysRemindRegister = SysRemindRegister.find(:first,:conditions=>["company_id = ? AND name = '借货归还' AND role_id = ?",session[:company_id],roleId])
      if sysRemindRegister === nil
        sysRemindRegister = SysRemindRegister.new
        sysRemindRegister.company_id = session[:company_id]
        sysRemindRegister.role_id = roleId
        sysRemindRegister.name = '借货归还'
        sysRemindRegister.is_register = 1
        sysRemindRegister.save!
      else
        sysRemindRegister.is_register = 1
        sysRemindRegister.save!
      end
    end

    if params[:product_stock] == nil
      sysRemindRegister = SysRemindRegister.find(:first,:conditions=>["company_id = ? AND name = '产品库存提醒' AND role_id = ?",session[:company_id],roleId])
      if sysRemindRegister != nil
        sysRemindRegister.is_register = 0
        sysRemindRegister.save!
      end
    else
      sysRemindRegister = SysRemindRegister.find(:first,:conditions=>["company_id = ? AND name = '产品库存提醒' AND role_id = ?",session[:company_id],roleId])
      if sysRemindRegister === nil
        sysRemindRegister = SysRemindRegister.new
        sysRemindRegister.company_id = session[:company_id]
        sysRemindRegister.role_id = roleId
        sysRemindRegister.name = '产品库存提醒'
        sysRemindRegister.is_register = 1
        sysRemindRegister.save!
      else
        sysRemindRegister.is_register = 1
        sysRemindRegister.save!
      end
    end

    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #重建索引
  def reindex
    #1.销售出库
    #2.销售退货入库
    #3.采购入库
    #4.采购退货出库
    #5.库间调货
    #6.货品拆分
    #7.货品组合
    #8.借货出库
    #9.借货返库
    #10.索赔出库
    #11.索赔返库
    #12.期初

    beginDate = params[:begin_date]
    endDate = params[:end_date]
    
    #删除所有在日期范围内的数据
    ProductCollection.delete_all("action_date BETWEEN '#{beginDate}' AND '#{endDate}'")
    #1.销售出库,只排除已经撤消的情况-------------------------------------------------
    #有占货这一说，所以只有撤消时才不让入汇总表。
    deliveryOrders = DeliveryOrder.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND auditing_status != ?",beginDate,endDate,Constants::PASS_APPLY_CANCEL],:include=>[:delivery_order_details])
    deliveryOrders.each do |deliveryOrder|
      deliveryOrderDetails = deliveryOrder.delivery_order_details
      deliveryOrderDetails.each do |deliveryOrderDetail|
        productCollection = ProductCollection.new
        productCollection.company_id = deliveryOrder.company_id
        productCollection.department_id = deliveryOrder.department_id
        productCollection.employee_id = deliveryOrder.employee_id
        productCollection.customer_id = deliveryOrder.customer_id
        productCollection.warehouse_id = deliveryOrder.warehouse_id

        productCollection.product_id = deliveryOrderDetail.product_id
        productCollection.quantity = 0 - deliveryOrderDetail.quantity
        productCollection.description =  deliveryOrderDetail.description
        #productCollection.discount = saleOrderDetail.discount
        #productCollection.unit_price = saleOrderDetail.unit_price
        #productCollection.unit_amount = 0 - deliveryOrderDetail.quantity * saleOrderDetail.unit_price
        productCollection.resource_id =  deliveryOrder.id
        productCollection.resource_type =  DeliveryOrder.name
        productCollection.action_date =  deliveryOrder.action_date
        productCollection.save!
      end
    end

    #2.销售退货入库---------------------------------------------------------------
    #只有入库时才入汇总表
    saleReturneds = SaleReturned.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND store_status = ?",beginDate,endDate,Constants::FINISH_ENTRY],:include=>[:sale_returned_details])
    saleReturneds.each do |saleReturned|
      saleReturnedDetails = saleReturned.sale_returned_details
      saleReturnedDetails.each do |saleReturnedDetail|
        productCollection = ProductCollection.new
        productCollection.company_id = saleReturned.company_id
        productCollection.department_id = saleReturned.department_id
        productCollection.employee_id = saleReturned.employee_id
        productCollection.customer_id = saleReturned.customer_id
        productCollection.warehouse_id = saleReturned.warehouse_id

        productCollection.product_id = saleReturnedDetail.product_id
        productCollection.quantity = saleReturnedDetail.quantity
        productCollection.description =  saleReturnedDetail.description
        #productCollection.discount = saleOrderDetail.discount
        #productCollection.unit_price = saleOrderDetail.unit_price
        #productCollection.unit_amount = 0 - deliveryOrderDetail.quantity * saleOrderDetail.unit_price
        productCollection.resource_id =  saleReturned.id
        productCollection.resource_type =  SaleReturned.name
        productCollection.action_date =  saleReturned.action_date
        productCollection.save!
      end
    end

    #3.采购入库---------------------------------------------------------------
    #有其实特殊性，只要生成的，就已经入库，没有审批流程
    warehousingEntries = WarehousingEntry.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND auditing_status != ? AND auditing_status != ''",beginDate,endDate,Constants::PASS_APPLY_CANCEL],:include=>[:warehousing_entry_details])
    warehousingEntries.each do |warehousingEntry|
      warehousingEntryDetails = warehousingEntry.warehousing_entry_details
      warehousingEntryDetails.each do |warehousingEntryDetail|
        productCollection = ProductCollection.new
        productCollection.company_id = warehousingEntry.company_id
        productCollection.department_id = warehousingEntry.department_id
        productCollection.employee_id = warehousingEntry.employee_id
        productCollection.vendor_id = warehousingEntry.vendor_id
        productCollection.warehouse_id = warehousingEntry.warehouse_id

        productCollection.product_id = warehousingEntryDetail.product_id
        productCollection.quantity = warehousingEntryDetail.quantity
        productCollection.description =  warehousingEntryDetail.description
        #productCollection.discount = saleOrderDetail.discount
        #productCollection.unit_price = saleOrderDetail.unit_price
        #productCollection.unit_amount = 0 - deliveryOrderDetail.quantity * saleOrderDetail.unit_price
        productCollection.resource_id =  warehousingEntry.id
        productCollection.resource_type =  WarehousingEntry.name
        productCollection.action_date =  warehousingEntry.action_date
        productCollection.save!
      end
    end

    #4.采购退货出库
    purchaseReturneds = PurchaseReturned.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND store_status = ?",beginDate,endDate,Constants::FINISH_DELIVERY],:include=>[:purchase_returned_details])
    purchaseReturneds.each do |purchaseReturned|
      purchaseReturnedDetails = purchaseReturned.purchase_returned_details
      purchaseReturnedDetails.each do |purchaseReturnedDetail|
        productCollection = ProductCollection.new
        productCollection.company_id = purchaseReturned.company_id
        productCollection.department_id = purchaseReturned.department_id
        productCollection.employee_id = purchaseReturned.employee_id
        productCollection.vendor_id = purchaseReturned.vendor_id
        productCollection.warehouse_id = purchaseReturned.warehouse_id

        productCollection.product_id = purchaseReturnedDetail.product_id
        productCollection.quantity = purchaseReturnedDetail.quantity
        productCollection.description =  purchaseReturnedDetail.description
        #productCollection.discount = saleOrderDetail.discount
        #productCollection.unit_price = saleOrderDetail.unit_price
        #productCollection.unit_amount = 0 - deliveryOrderDetail.quantity * saleOrderDetail.unit_price
        productCollection.resource_id =  purchaseReturned.id
        productCollection.resource_type =  PurchaseReturned.name
        productCollection.action_date =  purchaseReturned.action_date
        productCollection.save!
      end
    end

    #5.库间调货,调货没有撤消审批，
    transferOrders = TransferOrder.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND auditing_status != ? AND auditing_status != ? AND auditing_status != ?",beginDate,endDate,Constants::AUDIT_APPLY_ADD,Constants::REJECT_APPLY_ADD,Constants::PASS_APPLY_CANCEL],:include=>[:transfer_order_details])
    transferOrders.each do |transferOrder|
      transferOrderDetails = transferOrder.transfer_order_details
      transferOrderDetails.each do |transferOrderDetail|
        productCollection = ProductCollection.new
        productCollection.company_id = transferOrder.company_id
        productCollection.department_id = transferOrder.department_id
        productCollection.employee_id = transferOrder.employee_id
        productCollection.warehouse_id = transferOrder.from_warehouse_id
        productCollection.product_id = transferOrderDetail.product_id
        productCollection.quantity = 0 - transferOrderDetail.quantity
        productCollection.description =  transferOrderDetail.description
        productCollection.action_date =  transferOrder.action_date
        productCollection.resource_id =  transferOrder.id
        productCollection.resource_type =  TransferOrder.name
        productCollection.save!
        #以上为减，以下为加
        productCollection = ProductCollection.new
        productCollection.company_id = transferOrder.company_id
        productCollection.department_id = transferOrder.department_id
        productCollection.employee_id = transferOrder.employee_id
        productCollection.warehouse_id = transferOrder.to_warehouse_id
        productCollection.product_id = transferOrderDetail.product_id
        productCollection.quantity = transferOrderDetail.quantity
        productCollection.description =  transferOrderDetail.description
        productCollection.action_date =  transferOrder.action_date
        productCollection.resource_id =  transferOrder.id
        productCollection.resource_type =  TransferOrder.name
        productCollection.save!
      end
    end

    #6.货品拆分,拆分的处理方式上和调拨相似-------------------------------------------
    separateOrders = SeparateOrder.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND auditing_status != ? AND auditing_status != ? AND auditing_status != ?",beginDate,endDate,Constants::AUDIT_APPLY_ADD,Constants::REJECT_APPLY_ADD,Constants::PASS_APPLY_CANCEL],:include=>[:separate_order_details])
    separateOrders.each do |separateOrder|
      separateOrderDetails = separateOrder.separate_order_details
      #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
      productCollection = ProductCollection.new
      productCollection.company_id = separateOrder.company_id
      productCollection.department_id = separateOrder.department_id
      productCollection.employee_id = separateOrder.employee_id
      productCollection.warehouse_id = separateOrder.warehouse_id
      productCollection.action_date = separateOrder.action_date
      productCollection.product_id = separateOrder.product_id
      productCollection.quantity = 0 - separateOrder.quantity
      productCollection.description =  separateOrder.description
      productCollection.resource_id =  separateOrder.id
      productCollection.resource_type =  SeparateOrder.name
      productCollection.save!
      separateOrderDetails.each do |separateOrderDetail|
        productCollection = ProductCollection.new
        productCollection.company_id = separateOrder.company_id
        productCollection.department_id = separateOrder.department_id
        productCollection.employee_id = separateOrder.employee_id
        productCollection.warehouse_id = separateOrder.warehouse_id
        productCollection.action_date = separateOrder.action_date
        #productCollection.product_id = separateOrderDetail.product_id
        #productCollection.quantity = separateOrderDetail.quantity
        productCollection.product_id = separateOrderDetail.product_id
        productCollection.quantity = separateOrderDetail.quantity * separateOrder.quantity
        productCollection.description =  separateOrderDetail.description
        productCollection.resource_id =  separateOrder.id
        productCollection.resource_type =  SeparateOrder.name
        productCollection.save!
      end
    end

    #7.货品组合,拆分的处理方式上和调拨相似-------------------------------------------
    assemblyOrders = AssemblyOrder.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND auditing_status != ? AND auditing_status != ? AND auditing_status != ?",beginDate,endDate,Constants::AUDIT_APPLY_ADD,Constants::REJECT_APPLY_ADD,Constants::PASS_APPLY_CANCEL],:include=>[:assembly_order_details])
    assemblyOrders.each do |assemblyOrder|
      assemblyOrderDetails = assemblyOrder.assembly_order_details
      #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
      productCollection = ProductCollection.new
      productCollection.company_id = assemblyOrder.company_id
      productCollection.department_id = assemblyOrder.department_id
      productCollection.employee_id = assemblyOrder.employee_id
      productCollection.warehouse_id = assemblyOrder.warehouse_id
      productCollection.action_date = assemblyOrder.action_date

      productCollection.product_id = assemblyOrder.product_id
      productCollection.quantity = assemblyOrder.quantity
      productCollection.description =  assemblyOrder.description
      productCollection.resource_id =  assemblyOrder.id
      productCollection.resource_type =  AssemblyOrder.name
      productCollection.save!
      assemblyOrderDetails.each do |assemblyOrderDetail|        
        productCollection = ProductCollection.new
        productCollection.company_id = assemblyOrder.company_id
        productCollection.department_id = assemblyOrder.department_id
        productCollection.employee_id = assemblyOrder.employee_id
        productCollection.warehouse_id = assemblyOrder.warehouse_id
        productCollection.product_id = assemblyOrderDetail.product_id
        productCollection.quantity = 0 - (assemblyOrderDetail.quantity * assemblyOrder.quantity)
        productCollection.description =  assemblyOrderDetail.description
        productCollection.action_date = assemblyOrder.action_date
        productCollection.resource_id =  assemblyOrder.id
        productCollection.resource_type =  AssemblyOrder.name
        productCollection.save!
      end
    end

    #8.借货出库,借货出库的处理方式上和销售出库类似，都有占货这一操作。-------------------------------------------
    loanDeliveries = LoanDelivery.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND auditing_status != ?",beginDate,endDate,Constants::PASS_APPLY_CANCEL],:include=>[:loan_delivery_details])
    loanDeliveries.each do |loanDelivery|
      loanDeliveryDetails = loanDelivery.loan_delivery_details
      loanDeliveryDetails.each do |loanDeliveryDetail|
        #同时生成结算表的内容。
        productCollection = ProductCollection.new
        productCollection.company_id = loanDelivery.company_id
        productCollection.department_id = loanDelivery.department_id
        productCollection.employee_id = loanDelivery.employee_id
        productCollection.customer_id = loanDelivery.customer_id
        productCollection.warehouse_id = loanDelivery.warehouse_id

        productCollection.product_id = loanDeliveryDetail.product_id
        productCollection.quantity = 0 - loanDeliveryDetail.quantity
        productCollection.resource_id =  loanDelivery.id
        productCollection.resource_type =  LoanDelivery.name
        productCollection.action_date =  loanDelivery.action_date
        productCollection.save!
      end
    end

    #9.借货返库-------------------------------------------
    saleReturneds = SaleReturned.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND store_status = ?",beginDate,endDate,Constants::FINISH_ENTRY],:include=>[:sale_returned_details])
    saleReturneds.each do |saleReturned|
      saleReturnedDetails = saleReturned.sale_returned_details
      saleReturnedDetails.each do |saleReturnedDetail|
        #然后正式拆分此拆分单到结算表中。结算的方式就是主表是负数，然后拆分出来的产品是正数。
        productCollection = ProductCollection.new
        productCollection.company_id = saleReturned.company_id
        productCollection.department_id = saleReturned.department_id
        productCollection.employee_id = saleReturned.employee_id
        productCollection.customer_id = saleReturned.customer_id
        productCollection.warehouse_id = saleReturned.warehouse_id
        productCollection.action_date = saleReturned.action_date
        productCollection.product_id = saleReturnedDetail.product_id
        productCollection.quantity = saleReturnedDetail.quantity
        productCollection.description =  saleReturnedDetail.description
        productCollection.unit_price = saleReturnedDetail.unit_price
        productCollection.unit_amount = saleReturnedDetail.amount
        productCollection.amount = saleReturned.amount
        productCollection.resource_id =  saleReturned.id
        productCollection.resource_type =  SaleReturned.name
        productCollection.save!
      end
    end

    #10.索赔出库-------------------------------------------
    claims = Claim.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND (auditing_status = ? OR auditing_status = ?) AND auditing_status != ?",beginDate,endDate,Constants::PASS_APPLY_ADD,Constants::PASS_APPLY_EDIT,Constants::PASS_APPLY_CANCEL],:include=>[:claim_details])
    claims.each do |claim|
      claimDetails = claim.claim_details
      claimDetails.each do |claimDetail|
        #同时生成结算表的内容。
        productCollection = ProductCollection.new
        #copy内容到结算表
        #在进行成功转换后，要同时操作结算表，把此次操作的详细内容，完全拆解开，复制到结算表中。
        productCollection.company_id = claim.company_id
        productCollection.department_id = claim.department_id
        productCollection.employee_id = claim.employee_id
        productCollection.logistics_id = claim.logistics_id        
        productCollection.warehouse_id = claim.warehouse_id
        productCollection.product_id = claimDetail.product_id
        productCollection.quantity = 0 - claimDetail.quantity  #warehousingEntryDetail.quantity
        productCollection.description =  claimDetail.description
        #productCollection.unit_price = claimDetail.unit_price
        #productCollection.unit_amount = 0 - claimDetail.amount
        #productCollection.amount = 0 - claim.amount
        productCollection.resource_id =  claim.id
        productCollection.resource_type =  Claim.name

        productCollection.action_date = claim.action_date
        productCollection.purchase_order_id =  claimDetail.purchase_order_id
        productCollection.warehousing_entry_id =  claimDetail.warehousing_entry_id
        productCollection.save!
      end
    end

    #11.索赔返库-------------------------------------------
    claimReturneds = ClaimReturned.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND (auditing_status = ? OR auditing_status = ?) AND auditing_status != ?",beginDate,endDate,Constants::PASS_APPLY_ADD,Constants::PASS_APPLY_EDIT,Constants::PASS_APPLY_CANCEL],:include=>[:claim_details])
    claimReturneds.each do |claimReturned|
      claimReturnedDetails = claimReturned.claim_returned_details
      claimReturnedDetails.each do |claimReturnedDetail|
        #同时生成结算表的内容。
        productCollection = ProductCollection.new
        #copy内容到结算表
        #在进行成功转换后，要同时操作结算表，把此次操作的详细内容，完全拆解开，复制到结算表中。
        productCollection.company_id = claimReturned.company_id
        productCollection.department_id = claimReturned.department_id
        productCollection.employee_id = claimReturned.employee_id
        productCollection.logistics_id = claimReturned.logistics_id
        productCollection.warehouse_id = claimReturned.warehouse_id
        productCollection.product_id = claimReturnedDetail.product_id
        productCollection.quantity = claimReturnedDetail.quantity
        productCollection.description =  claimReturnedDetail.description
        #productCollection.amount = claimReturned.amount
        #productCollection.unit_price = claimReturnedDetail.unit_price
        #productCollection.unit_amount = claimReturnedDetail.amount
        productCollection.resource_id =  claimReturned.id
        productCollection.resource_type =  ClaimReturned.name

        productCollection.action_date = claimReturned.action_date
        productCollection.claim_id =  claimReturnedDetail.claim_id
        productCollection.save!
      end
    end

    #12.期初-------------------------------------------
    logger.info "12.期初......................................................."
    openingStocks = OpeningStock.find(:all,:conditions=>["(action_date BETWEEN ? AND ?) AND (auditing_status = ? OR auditing_status = ?) AND auditing_status != ?",beginDate,endDate,Constants::PASS_APPLY_ADD,Constants::PASS_APPLY_EDIT,Constants::PASS_APPLY_CANCEL],:include=>[:opening_stock_details])
    openingStocks.each do |openingStock|
      openingStockDetails = openingStock.opening_stock_details
      openingStockDetails.each do |openingStockDetail|
        productCollection = ProductCollection.new
        productCollection.company_id = openingStock.company_id
        productCollection.department_id = openingStock.department_id
        productCollection.employee_id = openingStock.employee_id
        productCollection.warehouse_id = openingStock.warehouse_id
        productCollection.product_id = openingStockDetail.product_id
        productCollection.quantity =  openingStockDetail.quantity
        productCollection.description =  openingStockDetail.description
        productCollection.action_date = openingStock.action_date
        productCollection.resource_id =  openingStock.id
        productCollection.resource_type =  OpeningStock.name
        productCollection.save!
      end
    end
    
    logger.info "Yes..................."
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #用户自行修改密码
  def changePassword
    employee =  Employee.find(session[:employee_id])
    employee.password = params[:password]
    employee.save!
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #计算成本价的页面
  def calCostPrice
    calYear = params[:action_date].split(/-/)[0]
    tempCalMonth = params[:action_date].split(/-/)[1]
    tempCalMonth = (tempCalMonth.to_i + 1).to_s
    if  tempCalMonth.to_s.length > 1
      endDate = calYear + "-" +tempCalMonth + "-01 00:00:00"
    else
      endDate = calYear + "-0" + tempCalMonth + "-01 00:00:00"
    end
    Product.cost_price endDate,calYear.to_i,params[:action_date].split(/-/)[1].to_i,session[:company_id],session[:employee_id]
    #Product.tax_price endDate,calYear.to_i,params[:action_date].split(/-/)[1].to_i,session[:company_id],session[:employee_id]
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #得到角色与可访问仓库的列表
  def getRoleWarehouse
    roleWarehouseIdArray = Array.new
    warehouseIdArray = Array.new
    warehouses = Warehouse.where("company_id = ?",session[:company_id])
    #先把需要的数据进行核对，如果当前的仓库，没有在角色仓库表中，就进行添加。

    RoleWarehouse.transaction do
      warehouses.each do |warehouse|
        roleWarehouses = RoleWarehouse.where("warehouse_id = ? AND role_id = ?",warehouse.id,params[:role_id])
        if roleWarehouses.length == 0
          roleWarehouse =  RoleWarehouse.new
          roleWarehouse.role_id = params[:role_id]
          roleWarehouse.warehouse_id = warehouse.id
          roleWarehouse.company_id = session[:company_id]
          roleWarehouse.employee_id = session[:employee_id]
          roleWarehouse.save!
        end
      end
    end
    #取所有的角色仓库数据。
    roleWarehouses = RoleWarehouse.joins("rw left join warehouses w on rw.warehouse_id = w.id").where("rw.company_id = ? AND rw.role_id = ?",session[:company_id],params[:role_id]).select("rw.id,rw.is_locked,w.name")
    jsonStr="{totalProperty:"+roleWarehouses.length.to_s+",root:"+roleWarehouses.to_json()+"}"
    logger.info jsonStr
    render :text=>jsonStr, :layout=>false
  end

  #角色，仓库的锁定与解锁
  def roleWarehouseLock
    roleWarehouse = RoleWarehouse.find(params[:id])
    if roleWarehouse.is_locked == 1
      roleWarehouse.is_locked = 0
    else
      roleWarehouse.is_locked = 1
    end
    roleWarehouse.save!
    info = "成功"
    result = "{success:true,info:'#{info}'}"
    render :text=>result, :layout=>false
  end

  #系统参数的设置，保存审批相关的参数状态。
  def updateAuditParams
    
  end
end
